package com.jiangnan.ui.activity

import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityAdminBookBinding
import com.jiangnan.entity.Book
import com.jiangnan.util.GlideUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AdminViewModel
import com.jiangnan.viewmodel.BookViewModel
import com.jiangnan.viewmodel.ISBNViewModel
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody

class AdminBookActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivityAdminBookBinding
    private var currentBook: Book? = null
    private lateinit var isbnViewModel: ISBNViewModel
    private lateinit var adminViewModel: AdminViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        binding = DataBindingUtil.setContentView(this, R.layout.activity_admin_book)
        isbnViewModel = ViewModelProvider(this).get(ISBNViewModel::class.java)
        adminViewModel = ViewModelProvider(this).get(AdminViewModel::class.java)
        binding.viewModel = adminViewModel
        binding.lifecycleOwner = this

        initUI()
        initObserve()

        binding.btnBookDelete.setOnClickListener(this)
        binding.btnBookUpdate.setOnClickListener(this)
        binding.btnUploadImg.setOnClickListener(this)


    }

    private fun initObserve() {
        /**
         * 监听上传封面图片的请求结果
         */
        isbnViewModel.coverUrl.observe(this){
            if (it.isNotEmpty()) {
                GlideUtil.loadImageWithPlaceholder(
                    this,
                    it,
                    R.drawable.img_default,
                    R.drawable.img_error,
                    binding.ivBookImg
                )
                // 更新封面路径
                currentBook?.img = it
            } else {
                ToastUtil.showShort(this, "上传封面失败")
            }
        }

        /**
         * 监听toast
         */
        adminViewModel.toastMessage.observe(this){
            ToastUtil.showShort(this, it)
        }
    }

    private fun initUI() {
        // 接收 Book 对象
        val book = intent.getParcelableExtra<Book>("book")
        currentBook = book
        book?.let {
            GlideUtil.loadImageWithPlaceholder(
                this,
                it.img ?: "",
                R.drawable.img_default,
                R.drawable.img_error,
                binding.ivBookImg
            )
            binding.etBookTitle.setText(it.title)
            binding.etBookIsbn.setText(it.isbn)
            binding.etBookAuthor.setText(it.author)
            binding.etBookSum.setText(it.sum)
            binding.etBookSummary.setText(it.summary)
            binding.etBookPublisher.setText(it.publisher)
            binding.etBookPubdate.setText(it.pubdate)
            binding.etBookPubplace.setText(it.pubplace)
            binding.etBookPages.setText(it.pages)
            binding.etBookPrice.setText(it.price)
            binding.etBookBinding.setText(it.binding)
            binding.etBookEdition.setText(it.edition)
            binding.etBookFormat.setText(it.format)
        }
    }

    override fun onClick(p0: View?) {
       when(p0?.id){
           binding.btnBookDelete.id -> {
               // 删除图书
               currentBook!!.id ?.let {
                   adminViewModel.deleteBookById(it)
               }
           }
           binding.btnBookUpdate.id -> {
               currentBook!!.title = binding.etBookTitle.text.toString().trim()
               currentBook!!.isbn = binding.etBookIsbn.text.toString().trim()
               currentBook!!.author = binding.etBookAuthor.text.toString().trim()
               var oldSum = currentBook!!.sum
               var nowSum = binding.etBookSum.text.toString().trim()
               currentBook!!.sum = nowSum
               var oldLastNum = currentBook!!.lastNum
               currentBook!!.lastNum = (oldLastNum!!.toInt() + nowSum.toInt() - oldSum!!.toInt()).toString()
               currentBook!!.summary = binding.etBookSummary.text.toString().trim()
               currentBook!!.publisher = binding.etBookPublisher.text.toString().trim()
               currentBook!!.pubdate = binding.etBookPubdate.text.toString().trim()
               currentBook!!.pubplace = binding.etBookPubplace.text.toString().trim()
               currentBook!!.pages = binding.etBookPages.text.toString().trim()
               currentBook!!.price = binding.etBookPrice.text.toString().trim()
               currentBook!!.binding = binding.etBookBinding.text.toString().trim()
               currentBook!!.edition = binding.etBookEdition.text.toString().trim()
               currentBook!!.format = binding.etBookFormat.text.toString().trim()
               // 更新图书
               currentBook?.let {
                   if(currentBook!!.author == null || currentBook!!.title == null || currentBook!!.isbn == null || currentBook!!.price == null){
                       ToastUtil.showShort(this,"必填信息不可为空")
                   }else if(currentBook!!.lastNum!!.toInt() < 0){
                       ToastUtil.showShort(this,"图书数量调整有误\n总数量已小于借出数量")
                   } else{
                       adminViewModel.updateBook(it)
                   }
               }

           }
           binding.btnUploadImg.id -> {
               // 上传图片
               getImageContent.launch("image/*")
               ToastUtil.showShort(this,"点击了修改封面按钮")
           }
       }
    }

    // 注册图片选择回调
    private val getImageContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { selectedUri ->
            // 从内容解析器中读取图片数据
            contentResolver.openInputStream(selectedUri)?.use { inputStream ->
                val bytes = inputStream.readBytes()
                // 构建 RequestBody（图片类型）
                val requestBody = bytes.toRequestBody("image/*".toMediaTypeOrNull())
                // 构造一个文件名，例如：cover_时间戳.jpg
                val fileName = "cover_${System.currentTimeMillis()}.jpg"
                // 构造 MultipartBody.Part 对象，字段名需和后端接收一致，这里假设为 "file"
                val part = MultipartBody.Part.createFormData("file", fileName, requestBody)
                // 调用 ViewModel 上传方法
                isbnViewModel.uploadCoverImage(part)
            }
        }
    }

}